use std::sync::Mutex;
use tauri_plugin_global_shortcut::{Code, Modifiers, Shortcut};
use crate::config::{AppConfigStore, ShortcutConfig};

/// 已解析的快捷键
#[derive(Clone)]
pub struct ParsedShortcuts {
    pub translate: Shortcut,
    pub screenshot: Shortcut,
    pub setting: Shortcut,
}

/// 快捷键状态存储
pub struct ShortcutStore {
    pub parsed_shortcuts: Mutex<Option<ParsedShortcuts>>,
}

impl ShortcutStore {
    pub fn new() -> Self {
        Self {
            parsed_shortcuts: Mutex::new(None),
        }
    }
}

/// 解析快捷键字符串
pub fn parse_shortcut(input: &str) -> Result<Shortcut, String> {
    let parts: Vec<&str> = input.split('+').collect();
    let mut mods: Option<Modifiers> = None;
    let mut code: Option<Code> = None;

    for token in parts.into_iter().map(|t| t.trim()) {
        match token {
            "CmdOrCtrl" | "CommandOrControl" => {
                let m = if cfg!(target_os = "macos") {
                    Modifiers::SUPER
                } else {
                    Modifiers::CONTROL
                };
                mods = Some(match mods {
                    Some(prev) => prev | m,
                    None => m,
                });
            }
            "Cmd" | "Command" => {
                mods = Some(match mods {
                    Some(prev) => prev | Modifiers::SUPER,
                    None => Modifiers::SUPER,
                });
            }
            "Ctrl" | "Control" => {
                mods = Some(match mods {
                    Some(prev) => prev | Modifiers::CONTROL,
                    None => Modifiers::CONTROL,
                });
            }
            "Alt" | "Option" => {
                mods = Some(match mods {
                    Some(prev) => prev | Modifiers::ALT,
                    None => Modifiers::ALT,
                });
            }
            "Shift" => {
                mods = Some(match mods {
                    Some(prev) => prev | Modifiers::SHIFT,
                    None => Modifiers::SHIFT,
                });
            }
            "Space" => {
                code = Some(Code::Space);
            }
            "," => {
                code = Some(Code::Comma);
            }
            other => {
                let c = other.chars().next().ok_or_else(|| "无效键".to_string())?;
                let u = c.to_ascii_uppercase();
                code = Some(match u {
                    'A' => Code::KeyA,
                    'B' => Code::KeyB,
                    'C' => Code::KeyC,
                    'D' => Code::KeyD,
                    'E' => Code::KeyE,
                    'F' => Code::KeyF,
                    'G' => Code::KeyG,
                    'H' => Code::KeyH,
                    'I' => Code::KeyI,
                    'J' => Code::KeyJ,
                    'K' => Code::KeyK,
                    'L' => Code::KeyL,
                    'M' => Code::KeyM,
                    'N' => Code::KeyN,
                    'O' => Code::KeyO,
                    'P' => Code::KeyP,
                    'Q' => Code::KeyQ,
                    'R' => Code::KeyR,
                    'S' => Code::KeyS,
                    'T' => Code::KeyT,
                    'U' => Code::KeyU,
                    'V' => Code::KeyV,
                    'W' => Code::KeyW,
                    'X' => Code::KeyX,
                    'Y' => Code::KeyY,
                    'Z' => Code::KeyZ,
                    _ => return Err(format!("暂不支持的键: {}", other)),
                });
            }
        }
    }
    let code = code.ok_or_else(|| "未检测到按键".to_string())?;
    Ok(Shortcut::new(mods, code))
}

/// 规范化快捷键字符串
pub fn normalize_shortcut_str(s: &str) -> String {
    if cfg!(target_os = "macos") {
        s.replace("CmdOrCtrl", "Cmd")
            .replace("CommandOrControl", "Cmd")
    } else {
        s.replace("CmdOrCtrl", "Ctrl")
            .replace("CommandOrControl", "Ctrl")
    }
}

/// 显示快捷键字符串
pub fn display_shortcut_str(s: &str) -> String {
    normalize_shortcut_str(s)
}

/// 填充标签（用于菜单显示）
pub fn pad_label(s: &str, width: usize) -> String {
    format!("{:<width$}", s, width = width)
}

/// 创建默认快捷键
pub fn create_default_shortcuts() -> ParsedShortcuts {
    ParsedShortcuts {
        translate: Shortcut::new(
            Some(if cfg!(target_os = "macos") {
                Modifiers::SUPER | Modifiers::SHIFT
            } else {
                Modifiers::CONTROL | Modifiers::SHIFT
            }),
            Code::KeyT,
        ),
        screenshot: Shortcut::new(
            Some(if cfg!(target_os = "macos") {
                Modifiers::SUPER | Modifiers::SHIFT
            } else {
                Modifiers::CONTROL | Modifiers::SHIFT
            }),
            Code::KeyS,
        ),
        setting: Shortcut::new(
            Some(if cfg!(target_os = "macos") {
                Modifiers::SUPER
            } else {
                Modifiers::CONTROL
            }),
            Code::Comma,
        ),
    }
}

/// Tauri 命令：获取快捷键配置
#[tauri::command]
pub fn get_shortcuts(state: tauri::State<AppConfigStore>) -> ShortcutConfig {
    state.cfg.lock().unwrap().shortcut.clone()
}

/// Tauri 命令：设置快捷键配置
#[tauri::command]
pub fn set_shortcuts(
    app: tauri::AppHandle,
    state: tauri::State<AppConfigStore>,
    shortcut_store: tauri::State<ShortcutStore>,
    translate: String,
    screenshot: String,
    setting: String,
) -> Result<(), String> {
    use tauri_plugin_global_shortcut::GlobalShortcutExt;
    
    let mgr = app.global_shortcut();
    mgr.unregister_all().map_err(|e| e.to_string())?;

    let translate_n = normalize_shortcut_str(&translate);
    let screenshot_n = normalize_shortcut_str(&screenshot);
    let setting_n = normalize_shortcut_str(&setting);

    let parsed = ParsedShortcuts {
        translate: parse_shortcut(&translate_n)?,
        screenshot: parse_shortcut(&screenshot_n)?,
        setting: parse_shortcut(&setting_n)?,
    };

    mgr.register(parsed.translate.clone())
        .map_err(|e| e.to_string())?;
    mgr.register(parsed.screenshot.clone())
        .map_err(|e| e.to_string())?;
    mgr.register(parsed.setting.clone())
        .map_err(|e| e.to_string())?;

    {
        let mut cfg = state.cfg.lock().unwrap();
        cfg.shortcut.translate = translate_n;
        cfg.shortcut.screenshot = screenshot_n;
        cfg.shortcut.setting = setting_n;
    }
    {
        let mut ps = shortcut_store.parsed_shortcuts.lock().unwrap();
        *ps = Some(parsed);
    }
    crate::config::save_config(&app, &state.cfg.lock().unwrap()).map_err(|e| e.to_string())?;
    Ok(())
}

